package com.vhall.component.framework.common.model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.vhall.component.framework.common.utils.TypeConverter;
import com.vhall.component.framework.common.utils.URLParser;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Data
@Slf4j
public class VhallInfo {

    /**
     * 用户 id
     */
    private Long userId;

    /**
     * 转发需要的参数
     */
    @JsonIgnore
    private List<String> var;

    /**
     * 构造转发参数
     *
     * @return
     */
    public String toZuulInfo() {
        StringBuilder builder = new StringBuilder();
        return URLParser.encodeUrl(builder.toString());
    }

    /**
     * 解析转发参数
     *
     * @return
     */
    public VhallInfo parseZullInfo(String builder) {
        if (Objects.isNull(builder)) {
            return null;
        }

        String url = URLParser.decodeUrl(builder);
        String[] infos = url.split(",");
        if (infos.length != 3) {
            return null;
        }

        final VhallInfo tenant = this;
        return tenant;
    }

    /**
     * 默认值
     *
     * @param obj
     * @return
     */
    String buildObject(Object obj) {
        return Objects.nonNull(obj) ? obj.toString() : "";
    }

    /**
     * @param date
     * @return
     */
    String buildDate(Date date) {
        return Objects.nonNull(date) ? String.valueOf(date.getTime()) : "";
    }

    /**
     * 解析参数
     *
     * @param o
     * @return
     */
    @SuppressWarnings("unchecked")
    <T> T parse(String o, Class<T> type) {
        try {
            if (o.length() > 0) {
                if (String.class == type) {
                    return (T) o;
                }
                if (Boolean.class == type) {
                    return (T) TypeConverter.toBoolean(o);
                }
                if (Integer.class == type) {
                    return (T) TypeConverter.toInteger(o);
                }
                if (Long.class == type) {
                    return (T) TypeConverter.toLong(o);
                }
            }
        } catch (Exception e) {
            log.error("vhall-info parse error:", e);
        }
        return null;
    }

}
